<template>
    <div class="app-container">
      <el-form :show-message="!($route.query.isInfo || isInfo)" ref="elForm" :disabled="$route.query.isInfo || isInfo"
        :model="formData" :rules="rules" size="medium" label-width="120px">
        <h2 style="text-align: center">计算机/自动设备校核记录表</h2>
        <h4 class="form-header h4">内部审核</h4>
        <el-row :gutter="15">
          <el-col :span="8">
            <el-form-item label="年度" prop="planYear">
              <el-date-picker type="year" v-model="formData.planYear" format="yyyy" value-format="yyyy"
                :style="{ width: '100%' }" placeholder="请选择年度" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内审开始时间" prop="startAuditDate">
              <el-date-picker v-model="formData.startAuditDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :style="{ width: '100%' }" placeholder="请选择内审开始时间" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内审结束时间" prop="endAuditDate">
              <el-date-picker v-model="formData.endAuditDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                :style="{ width: '100%' }" placeholder="请选择内审结束时间" clearable></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="被审核部门" prop="deptId">
              <el-cascader ref="reference" :style="{ width: '100%' }"
                :props="{ value: 'id', checkStrictly: true, multiple: true }" :value-format="valueFormat"
                :show-all-levels="false" placeholder="请选择部门" v-model="formData.deptId" :options="deptOptions"
                @change="changeCascader"></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="内审组组长" prop="leaderId">
              <UserDialog :disabled="$route.query.isInfo || isInfo" v-model="formData.leaderId" @change="changeUser">
              </UserDialog>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="16">
            <el-form-item label="内审组成员" prop="userIdIn">
              <UserDialogSelection :disabled="$route.query.isInfo || isInfo" @change="changeOpen" placeholder="请选择内审组成员"
                v-model="formData.userIdIn"></UserDialogSelection>
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-form-item label="是否启用" prop="effectStatus">
          <el-switch
            v-model="formData.effectStatus"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item> -->
        <el-form-item label="审核要素">
          <div>
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
              <el-checkbox v-for="dict in cities" :label="dict" :key="dict.content">{{ dict.content }}</el-checkbox>
            </el-checkbox-group>
          </div>
  
          <!-- <el-input v-model="formData.element" type="textarea" placeholder="请输入多行文本审核要素"
            :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input> -->
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入多行文本备注" :autosize="{ minRows: 4, maxRows: 4 }"
            :style="{ width: '100%' }"></el-input>
        </el-form-item>
        <h4 class="form-header h4">
          具体工作安排
          <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
          <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button>
        </h4>
        <el-table :data="formData.itemList" :border="true" style="width: 100%">
          <el-table-column label="序号" type="index" align="center" />
          <!-- <el-table-column v-model="userIdList" label="人员" width="200" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`itemList.${scope.$index}.userId`" :rules="rules.userId">
                <UserDialog :disabled="$route.query.isInfo || isInfo" @change="chanageUser($event, scope.$index)"
                  v-model="scope.row.userId"></UserDialog>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column label="具体工作时间" type="element" align="center" width="500px">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.time" @change="changTime($event, scope.$index)"
                value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
              <!-- <el-date-picker v-model="scope.row.time" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker> -->
            </template>
          </el-table-column>
          <el-table-column label="具体工作" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`itemList.${scope.$index}.doWork`" :rules="rules.doWork">
                <el-input v-model="scope.row.doWork" placeholder="请输入具体工作"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 内部审核员工 -->
        <h4 class="form-header h4">
          内审组成员
          <el-button type="primary" plain size="mini" @click="handleAddUser">增行</el-button>
          <el-button type="danger" plain size="mini" @click="handleDeleUser">删行</el-button>
        </h4>
        <el-table :data="formData.userList1" :border="true" style="width: 100%">
          <el-table-column label="序号" type="index" align="center" width="100px">
            <template slot-scope="scope">
              第{{ scope.$index + 1 }}小组
            </template>
          </el-table-column>
          <el-table-column label="内审组人员" width="200" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`userList1.${scope.$index}.userId`" :rules="rules.userId">
                <!-- <UserDialog
                  :disabled="$route.query.isInfo || isInfo"
                  @change="chanageUser($event, scope.$index)"
                  v-model="scope.row.userId"
                ></UserDialog> -->
                <UserDialogSelection :disabled="$route.query.isInfo || isInfo" @change="changeOpen($event, scope.$index)"
                  placeholder="请选择内审组成员" v-model="scope.row.userId"></UserDialogSelection>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="被审核部门" align="center">
            <template slot-scope="scope">
              <el-form-item label-width="0" :prop="`userList1.${scope.$index}.deptId`" :rules="rules.deptId">
                <el-cascader ref="references" :style="{ width: '100%' }"
                  :props="{ value: 'id', checkStrictly: true, multiple: true }" :show-all-levels="false" placeholder="请选择部门"
                  v-model="scope.row.deptId" :options="deptOptions" @change="changeCascaderNums"
                  @visible-change="visibleChange($event, scope.$index)"></el-cascader>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
  
        <el-col :span="24" v-if="btnShow">
          <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
            <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm">提交</el-button>
            <el-button :disabled="false" @click="resetForm">返回</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
  </template>
  
  <script>
  //  const cityOptions = ['上海', '北京', '广州', '深圳'];
  import store from "@/store";
  import { deptTreeSelect } from "@/api/system/user";
  import {getParentList} from '@/api/quality/inAudit.js'
  import Vue from 'vue';
  import {
    auditPlanAdd,
    updategauditPlan,
    auditPlanInfo,
  } from "@/api/quality/inAudit.js";
  
  export default {
    components: {},
    dicts: ["verify_key_element"],
    props: {
      isInfo: {
        type: Boolean,
        default: false,
      },
      id: {
        type: String,
        default: "",
      },
      btnShow: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        postOptions: [],
        isIndeterminate: true,
        checkAll: false,
        formData: {
          planYear: undefined,
          itemList: [{ doWork: "", userId: "", userName: "" }],
          userList1: [{ deptId: "", deptName: '', userId: "", userName: "", }],
  
          startAuditDate: undefined,
          startAuditDate: undefined,
          leaderId: undefined,
          element: undefined,
          remark: undefined,
          deptId: undefined,
          userId: [],
          startDate: "",
          applyDate: null,
          toOfficialDate: "",
          tryEndDate: "",
        },
        checkedCities: [],
        cities: [],
        rules: {
          planYear: [
            {
              required: true,
              message: "请选择年份",
              trigger: "change",
            },
          ],
          element: [
            {
              required: true,
              message: "请输入审查要素",
              trigger: "blur",
            },
          ],
          endAuditDate: [
            {
              required: true,
              message: "请选择内审开始时间",
              trigger: "change",
            },
          ],
          startAuditDate: [
            {
              required: true,
              message: "请选择内审结束时间",
              trigger: "change",
            },
          ],
          leaderId: [
            {
              required: true,
              message: "请选择组长",
              trigger: "change",
            },
          ],
          deptId: [
            {
              required: true,
              message: "请选择部门",
              trigger: "change",
            },
          ],
          userId: [
            {
              required: true,
              message: "请选择组员",
              trigger: "blur",
            },
          ],
          // userId: [
          //   {
          //     required: true,
          //     message: "请选择人员",
          //     trigger: "change",
          //   },
          // ],
          doWork: [
            {
              required: true,
              message: "请输入具体工作",
              trigger: "blur",
            },
          ],
        },
        userList: [],
        deptId: [],
        deptOptions: [],
        deptIdStringValue: '',
        deptIdStringLabel: '',
        cityOptions: [],
        showGroup: false
      };
    },
    computed: {},
    watch: {},
    created() {
      this.getDeptTree();
  
      // this.cities = this.dict.type.verify_key_element
      console.log(this.dict.type.verify_key_element);
      this.getParentList()
      if (this.$route.query.isEdit || this.$route.query.isInfo || this.isInfo) {
        this.getinfo();
      }
  
    },
    mounted() {
    },
    methods: {
      getParentList(){
        getParentList().then((res)=>{
          if(res.code == 200){
            this.cities = res.data
          }
        })
      },
      handleCheckAllChange(val) {
        console.log(val);
        this.checkedCities = val ? this.cities : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        console.log(value);
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.cities.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
        console.log(this.checkedCities);
      },
      changeCascader(e) {
        console.log(this.$refs.reference.getCheckedNodes());
        let arr = this.$refs.reference.getCheckedNodes()
        let list = []
        let label = []
        arr.forEach((item, index) => {
          list.push(item.value)
          label.push(item.label)
          console.log(item.value);
        })
        console.log(list);
        this.deptIdStringValue = list.toString()
        this.deptIdStringLabel = label.toString()
        console.log(this.deptIdStringValue, this.deptIdStringLabel);
      },
      changeCascaderNums(e, i) {
        console.log(e, i);
        this.showGroup = e.length > 0 ? true : false
      },
      visibleChange(e, i) {
        console.log(e);
        if (!e && this.showGroup) {
          let arr = this.$refs.references.getCheckedNodes()
          let list = []
          let label = []
          arr.forEach((item, index) => {
            list.push(item.value)
            label.push(item.label)
          })
          console.log(list);
          this.formData.userList1[i].deptIdReplace = list.toString()
          this.formData.userList1[i].deptNameReplace = label.toString()
          // console.log(this.formData.userList1[i].deptName, 'this.formData.userList1[i].deptId');
        }
  
      },
      changTime(e, i) {
        console.log(e, i);
        this.formData.itemList[i].startTime = e[0]
        this.formData.itemList[i].endTime = e[1]
  
      },
      chanageUser(e, i) {
        this.formData.itemList[i].userName = e.nickName;
      },
      handleAdd() {
        this.formData.itemList.push({ doWork: "", userId: "", userName: "" });
      },
      handleAddUser() {
        this.formData.userList1.push({ deptId: "", userId: "", userName: "", deptName: '' });
      },
      handleDeleUser() {
        if (this.formData.userList1.length == 1) return;
        this.formData.userList1.pop();
      },
      handleDele() {
        if (this.formData.itemList.length == 1) return;
        this.formData.itemList.pop();
      },
      changeOpen(e, i) {
        console.log(e, i);
        // this.formData.userList1 =
        let idList = []
        let nameList = []
        e.forEach((i) => {
          // return { userId: i.userId, userName: i.nickName };
          idList.push(i.userId)
          nameList.push(i.nickName)
        });
        console.log(idList, 'idList');
        this.formData.userList1[i].userId = idList.toString()
        this.formData.userList1[i].userName = nameList.toString()
        // this.formData.userList1[i].userId.toString()
        // console.log(this.formData.userList1[i].userId,'this.formData');
      },
      changeUser(e) {
        console.log(e);
        this.formData.leaderName = e.nickName;
      },
      /** 查询部门下拉树结构 */
      getDeptTree() {
        deptTreeSelect().then((response) => {
          this.deptOptions = response.data;
          // this.formData.deptId = store.state.user.dept.deptId
        });
      },
      valueFormat(value) {
        return value[value.length - 1];
      },
      getinfo() {
        return auditPlanInfo(this.$route.query.id || this.id).then((response) => {
          this.formData = response.data;
          this.formData.userIdIn = response.data.userList.map((e) => e.userId);
          // 具体工作安排回显时间
          this.formData.itemList.forEach(item => {
            item.time = []
            item.time.push(item.startTime, item.endTime)
          })
          // 
          this.formData.userList.forEach(item => {
            let list1 = []
            item.deptId = item.deptId.split(',')
            item.deptId = item.deptId.map(i => parseInt(i))
            console.log(item.deptId, 'item.deptId');
            item.deptName = item.deptName.split(',')
            item.userId = item.userId.split(',')
            item.userName = item.userName.split(',')
            item.deptId.map(i => {
              list1.push(this.findParentLot(i))
            })
            item.deptId = list1
          })
          this.formData.userList1 = this.formData.userList
          // this.checkedCities = this.formData.elementVos
          let arr = []
          this.formData.elementVos.forEach(item => {
            const obj = Vue.observable({
              label: item.dataLabel,
              value: item.dataValue,
            })
            arr.push(obj)
          })
          this.checkedCities= arr
          console.log(this.checkedCities);
          this.formData.deptId = this.formData.deptId.split(',')
          // this.formData.deptId = [[100,110],[100,110,111,115],[100,110,111,118]]
          // 将ID转number类型
          this.formData.deptId = this.formData.deptId.map(i => parseInt(i))
          let list = []
          // 多选部门回显取后端返回的ID
          this.formData.deptId.map(i => {
            list.push(this.findParentLot(i))
          })
          this.formData.deptId = list
        });
      },
      // 创建新数组 返回
      findParentLot(id) {
        const arr = []
        this.deployIdFun(this.deptOptions, id, arr)
        return arr.reverse()
      },
      // 逻辑代码 for循环 判断相同的id 取上级ID
      deployIdFun(options, id, newArr) {
        // console.log(options);
        options.forEach((v) => {
          if (v.id === id) {
            newArr.push(id)
            // console.log(newArr, 'newArr');
            if (!v.parentId || v.parentId !== '0') {
              this.deployIdFun(this.deptOptions, v.parentId, newArr)
            }
          } else {
            if (v.children && v.children.length) {
              this.deployIdFun(v.children, id, newArr)
            }
          }
        })
      },
      submitForm() {
        console.log(this.checkedCities);
        // console.log(this.$refs.reference.getCheckedNodes());
        this.$refs["elForm"].validate((valid) => {
          if (valid) {
            
            if (this.checkedCities.length > 0) {
              let arr = []
              this.checkedCities.forEach(item => {
                const obj = {
                  dataCode: item.innerCheckContentSettingId,
                  dataValue: item.dictValue,
                  dataLabel: item.type + item.content,
                  innerAuditPlanId: this.formData.innerAuditPlanId ? this.formData.innerAuditPlanId : null
                }
                arr.push(obj)
              })
              this.formData.elementList = arr
              console.log(this.formData.elementList);
            }
            this.formData.userList1.forEach(i => {
              i.userId = i.userId.toString()
              i.deptId = i.deptIdReplace
              i.deptName = i.deptNameReplace
              // delete i.deptIdReplace
              // delete i.deptNameReplace
            })
            this.formData.userList = this.formData.userList1
            let query = JSON.parse(JSON.stringify(this.formData));
            // query.deptId = this.$refs.reference.getCheckedNodes()[0].value;
            query.deptId = this.deptIdStringValue
            // query.deptName = this.$refs.reference.getCheckedNodes()[0].label;
            query.deptName = this.deptIdStringLabel
  
            if (this.formData.innerAuditPlanId != undefined) {
              updategauditPlan(query).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.resetForm();
              });
            } else {
              auditPlanAdd(query).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.resetForm();
              });
            }
          }
        });
      },
      resetForm() {
        this.$tab.closeOpenPage();
        // if (this.$route.query.iszzlist) {
        //   const obj = { path: "./zzsqList" };
        //   this.$tab.closeOpenPage(obj);
        // } else {
        //   const obj = { path: "./contract" };
        //   this.$tab.closeOpenPage(obj);
        // }
      },
    },
  };
  </script>
  <style lang="scss" scoped>
  ::v-deep .el-form-item {
    margin-top: 20px !important;
  }
  </style>
  